<?php

class UploadFile
{
    /**
     * 上传路径
     * @var string
     */
    public $upload_path = 'uploads';

    /**
     * 获取文件开证明
     * @param $file
     * @return mixed|string
     */
    function get_extension($file)
    {
        $info = pathinfo($file);
        return $info['extension'];
    }

    /**
     * 执行上传
     * @return false|string
     */
    function doUpload()
    {
        $file = $_FILES['file'];

        if ($_FILES["file"]["error"] > 0) {
            exit( json_encode(['code' => 500, 'msg' => $_FILES["file"]["error"]]));
        }
        $allowedMimeTypes = ['audio/mpeg', 'audio/ogg', 'audio/wav'];

        // 检查上传文件的 MIME 类型
        if (!in_array($file['type'], $allowedMimeTypes)) {
            exit( json_encode(['code' => 500, 'msg' => '文件类型错误']));
        }
        $ext = $this->get_extension($_FILES["file"]["name"]);

        if (!is_dir($this->upload_path)) {
            mkdir($this->upload_path, 777);
        }

        $path = "uploads/" . uniqid() . '.' . $ext;
        // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
        move_uploaded_file($_FILES["file"]["tmp_name"], $path);
        exit( json_encode(['code' => 200, 'path' => $path]));

    }
}


$upload = new UploadFile();
return $upload->doUpload();




